<?php

namespace App\Http\Controllers\Admin;

use App\Admin\SampleInfo;
use App\Http\Controllers\Api\CqydApiController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Cache;
use Log;

class ItemDataController_back extends Controller
{
    /*绑定内网项目中的试验数据key*/
    public function bindUploadKey(){
        $id = request('id','');
        $res = DB::table('a_testdata_key')->where('id',$id)->update([
            'upload_key'=>request('upload_key',''),
            'upload_unit'=>request('upload_unit',''),
            'upload_bei'=>request('upload_bei',''),
        ]);
        return $res ? 1 : 0;
    }

    /*绑定内网项目ID*/
    public function bindThirdItem(){
        $id = request('id','');
        $itemData = DB::table('a_item_data as a')->leftJoin('a_contract_gaiyao as b','a.contract_gaiyao_id','=','b.id')->where('a.id',$id)->select('a.item_id','b.tool_id')->first();

        if(request()->isMethod('post')){
            $code = request('third_item_code','');
            $res = DB::table('a_std_tool_item_rel')->where([
                'tool_id'=>$itemData->tool_id,
                'testitem_id'=>$itemData->item_id,
            ])->update(['third_item_code'=>$code]);
            return $res ? 1 : 0;
        }
        if(request()->isMethod('get')){
            $code = DB::table('a_std_tool_item_rel')->where([
                'tool_id'=>$itemData->tool_id,
                'testitem_id'=>$itemData->item_id,
            ])->value('third_item_code');
            return $code;
        }
    }
    //a_item_data表中的状态
    public static function dbStat() {
        return [
            'res'    => [
                0 => '不符合',
                1 => '符合',
                2 => '未录入',
                3 => '未试验',
            ],
            'commit' => [
                '-1' => '被驳回',
                0    => '未提交',
                1    => '已提交',
                2    => '审核通过',
            ]
        ];
    }

    /* 检测设备列表 */
    public function station() {
        if(request()->expectsJson()) {
            //ajax请求
            //查询准用和在用的设备
            $data = DB::table('a_station')->whereIn('status', [1, 2])->orderBy('dev_num')->get();
            $jsonData['data'] = $data;
            return response()->json($jsonData);
        }
        else {
            $statonObj = new StationController();
            $data = $statonObj->dbStat();
            return view('admin.itemData.station', compact('data'));
        }
    }

    public function resLuru($request, $sample_info_id) {
        if(!$sample_info_id) {
            return '参数错误！';
        }
        $item_data_id = $request->item_id; //a_item_data 表的id
        $itemInfo = DB::table('a_item_data')->where('id', $item_data_id)->first();
        $commit = $itemInfo->commit;
        if($commit > 0) {
            //如果该样品已提交，则不允许保存
            return '2';
        }
        $update = [
            'remark'      => $request->remark,
            'res'         => $request->res,
            'station_ids' => $request->station_ids,
            'utime'       => $request->utime
        ];
        if($item_data_id != 61) { //如果不是外观检查添加环境信息
            $updateEnv = [
                'wea'      => $request->wea,
                'temp'     => $request->temp,
                'hum'      => $request->hum,
                'pressure' => $request->pressure,
            ];
            $update = array_merge($update, $updateEnv);
        }
        $res = DB::table('a_item_data')->where('id', $item_data_id)->update(ary_filter($update));
        if($newStaIds = $request->station_ids) {
            //获取之前的station_ids,并根据差异值操作次数
            $oldStaIds = explode(',', request('old_station_ids', ''));
            $newStaIds = explode(',', $newStaIds);
            $decStdIds = array_diff($oldStaIds, $newStaIds);
            $incStdIds = array_diff($newStaIds, $oldStaIds);
            $newStaIdStr = implode(',', $newStaIds);
            //修改检测设备的使用次数
            if($decStdIds) {
                DB::table('a_station')->whereIn('id', $decStdIds)->decrement('used_num', 1);
            }
            if($incStdIds) {
                DB::table('a_station')->whereIn('id', $incStdIds)->increment('used_num', 1);
            }
            //修改工器具--检测项目对应的默认检测设备
            $tool_id = DB::table('a_contract_gaiyao')->where('id', $itemInfo->contract_gaiyao_id)->value('tool_id');
            DB::table('a_std_tool_item_rel')->where(['tool_id' => $tool_id, 'testitem_id' => $itemInfo->item_id])->update(['station_ids' => $newStaIdStr]);
        }

        //缓存温度 30min
        Cache::put('temp', $request->temp, 30);
        //缓存湿度 30min
        Cache::put('hum', $request->hum, 30);

        //缓存天气 60*4 min
        Cache::put('wea', $request->wea, 60*4);
        //缓存气压 60*4 min
        Cache::put('pressure', $request->pressure, 60*4);

        $arr = $request->val;
        if($arr) {
            # 如果$arr 不为null 就遍历，遍历null会报错
            foreach($arr as $k => $v) {
                $result = DB::table('a_input_data')->where('id', $k)->update(['val' => $v]);
            }
        }


        //如果没有不合格的，删除不合格照片
        if(DB::table('a_item_data')->where(['sample_info_id' => $sample_info_id, 'res' => 0])->count() === 0) {
            $non_photo = DB::table('a_sample_info')->where('id', $sample_info_id)->value('non_photo');
            @unlink(substr($non_photo, 1));
        }

        //录入结果后，分析一下当前样品的所有项目的结果情况
        // 结论, 0 - 不符合，1 - 符合，2 - 未录入  ，3-未试验
        //如果所有项目全部符合即合格，等价于 不符合或未录入的记录数为0
        $sql = "SELECT
        count( 1 ) AS count
        FROM
        a_item_data
        WHERE
        sample_info_id = :sample_info_id
        AND ( res != 1 ) ";

        $count = DB::select($sql, ['sample_info_id' => $sample_info_id]);
        $count = $count[0]->count;
        if($count === 0) {
            DB::table('a_sample_info')->where('id', $sample_info_id)->update(['res' => '1', 'status0' => 0, 'non_photo' => '']); //合格,未提交
        }
        else {
            //如果存在不符合的记录，说明此样品不合格
            $count0 = DB::table('a_item_data')->where([['sample_info_id', '=', $sample_info_id], ['res', '=', '0']])->count();

            if($count0 > 0) {
                DB::table('a_sample_info')->where('id', $sample_info_id)->update(['res' => '2']); //不合格
            }
            else {
                DB::table('a_sample_info')->where('id', $sample_info_id)->update(['res' => '0']); //未完成
            }
            $count2 = $count - $count0;
            $items_data_total = DB::table('a_item_data')->where('sample_info_id', $sample_info_id)->count();  //当前工器具下的检测总数量
            if($count2 > 0 && $count2 < $items_data_total) {
                DB::table('a_sample_info')->where('id', $sample_info_id)->update(['status0' => 4]); //试验中
            }
            if($count2 === 0) {
                DB::table('a_sample_info')->where('id', $sample_info_id)->update(['status0' => 0]); //未提交
            }
        }

        $this->updateTester($sample_info_id);  //更新 a_sample_info 表的检验人员

        //更新 a_sample_info 表的试验时间
        $test_time = DB::table('a_item_data')->where('sample_info_id', $sample_info_id)->max('utime'); //把当前样品所有检测项目的最新检测时间作为检测时间
        $r = DB::table('a_sample_info')->where('id', $sample_info_id)->update(['test_time' => $test_time]);

        //更新检验时间及到期时间
        $this->updateTestTime_NextTime($sample_info_id);
        return '1';
    }

    /* 分项目结果录入 页面展示 */
    public function index(Request $request) {
        //获取 sample_info 的id
        $sample_info_id = $request->id;
        if($request->isMethod('POST')) {
            if(config('constant.app_name') == 'ChongQingYuDian'){
                $params = request()->all();
                if($res != 1) {
                    return $res;
                }
            }
            return $this->resLuru($request, $sample_info_id);
        }
        else {
            $sample_info_data = DB::table('a_sample_info')->find($sample_info_id);
            $gaiyao_data = DB::table('a_contract_gaiyao')->find($sample_info_data->contract_gaiyao_id);
            $cycle = DB::table('a_std_tool_rel')->where('std_id', $gaiyao_data->std_id)->where('tool_id', $gaiyao_data->tool_id)->value('cycle'); //周期

            $contract_id = $sample_info_data->contract_id; //批次 id

            //获取下一个样品的id
            $sample_id_next = DB::table('a_sample_info')->where('id', '>', $sample_info_id)->where('contract_id', $contract_id)->orderBy('id', 'asc')->value("id");
            //获取上一个样品的id
            $sample_id_pre = DB::table('a_sample_info')->where('id', '<', $sample_info_id)->where('contract_id', $contract_id)->orderBy('id', 'desc')->value("id");

            $sql = "SELECT
            A.id,
            A.commit,
            A.item_id,
            A.wea,
            A.pressure,
            A.temp,
            A.hum,
            A.remark,
            A.station_ids,
            A.utime,
            A.res,
            A.manager_id,
            A.device_ids,
            A.allot_time,
            B.`name`
            FROM
            a_item_data AS A
            LEFT JOIN a_testitem AS B ON A.item_id = B.id
            LEFT JOIN a_contract_gaiyao AS D ON A.contract_gaiyao_id = D.id
            LEFT JOIN a_std_tool_item_rel AS E ON D.std_id = E.std_id
            AND D.tool_id = E.tool_id
            AND A.item_id = E.testitem_id
            WHERE
            A.sample_info_id = {$sample_info_id} ";
            if(!isAdmin()) {
                $sql .= " AND A.manager_id = ".auth('admin')->user()->id;
            }
            $sql .= " ORDER BY
            E.sort ASC ";

            $items_data = DB::select($sql);
            //当前样品 分配给 当前主检人 的项目是否已提交
            $commit = DB::table('a_item_data')->where('sample_info_id', $sample_info_id)->where('manager_id', auth('admin')->user()->id)->value('commit');

            $bindItem = [];
            if(config('constant.app_name') === 'ChongQingYuDian'){
                $cqydCon = new CqydApiController();
                $res = $cqydCon->getItems($sample_info_data->third_id);
                $res = json_decode($res,true);
                if($res['code'] == 0){
                    $bindItem = $res['data'];
                }
            }

            //获取批次的详细信息
            return view('admin.itemData.index', compact('items_data', 'sample_info_data', 'gaiyao_data', 'cycle', 'commit', 'sample_id_next', 'sample_id_pre','bindItem'));
        }
    }

    //更新 a_sample_info 表的 试验时间 和 下次试验时间
    public function updateTestTime_NextTime($sample_info_id, $std_id='', $tool_id='') {
        //更新 a_sample_info 表的试验时间
        // $test_time = date("Y/m/d"); //把当前时间作为检测时间
        $test_time = DB::table('a_item_data')->where('sample_info_id', $sample_info_id)->max('utime');              //把当前样品所有检测项目的最新检测时间作为检测时间
        DB::table('a_sample_info')->where('id', $sample_info_id)->update(['test_time' => $test_time]);
        if($std_id == '' || $tool_id == ''){
            $gaiyao_data = DB::table('a_contract_gaiyao as a')->leftJoin('a_sample_info as b','a.id','=','b.contract_gaiyao_id')->where('b.id',$sample_info_id)->select('std_id','tool_id')->first();
            $std_id = $gaiyao_data->std_id;
            $tool_id = $gaiyao_data->tool_id;
        }
        //获取检验周期
        $cycle = DB::table('a_std_tool_rel')->where('std_id', $std_id)->where('tool_id', $tool_id)->value('cycle'); //周期
        $cycle = intval($cycle*12);
        if($cycle > 0) {
            $valid_date = date("Y-m-d", strtotime("+$cycle month", strtotime($test_time)));
            $first_date = date("Y-m-d", strtotime("first day of +$cycle month", strtotime($test_time)));
            if(substr($valid_date, 0, 7) !== substr($first_date, 0, 7)) {
                $valid_date = date("Y-m-d", strtotime("last day of +$cycle month", strtotime($test_time)));
            }
            $sampleinfo = DB::table('a_sample_info')->find($sample_info_id);
            $time = strtotime($valid_date);
            if($sampleinfo->force_scrap_date && ($time > strtotime($sampleinfo->force_scrap_date))){
                $valid_date = $sampleinfo->force_scrap_date;
            }else{
                $valid_date = date('Y-m-d', strtotime("-1 day", $time));
            }
            //更新 a_sample_info 表的下次试验时间
            DB::table('a_sample_info')->where('id', $sample_info_id)->update(['next_time' => $valid_date]);
        }
    }

    //更新 a_sample_info 表的 结论（res）
    public function updateJieLun($sample_info_id) {
        //录入结果后，分析一下当前样品的所有项目的结果情况
        // 结论, 0 - 不符合，1 - 符合，2 - 未录入
        //如果所有项目全部符合即合格，等价于 不符合或未录入的记录数为0
        $sql = "SELECT
        count( 1 ) AS count
        FROM
        a_item_data
        WHERE
        sample_info_id = :sample_info_id
        AND ( res = 0 OR res = 2 ) ";

        $count = DB::select($sql, ['sample_info_id' => $sample_info_id]);
        $count = $count[0]->count;
        if($count === 0) {
            DB::table('a_sample_info')->where('id', $sample_info_id)->update(['res' => '1']); //合格
        }
        else {
            //如果存在不符合的记录，说明此样品不合格
            $count = DB::table('a_item_data')->where([['sample_info_id', '=', $sample_info_id], ['res', '=', '0']])->count();
            if($count > 0) {
                DB::table('a_sample_info')->where('id', $sample_info_id)->update(['res' => '2']); //不合格
            }
            else {
                DB::table('a_sample_info')->where('id', $sample_info_id)->update(['res' => '0']); //未完成
            }
        }
    }

    //更新 a_sample_info 表的检验人员
    public function updateTester($sample_info_id) {
        $tester_names = DB::table('a_item_data as a')
        ->leftJoin('manager as b', 'a.manager_id', '=', 'b.id')
        ->leftJoin('manager as c', 'b.partner', '=', 'c.realname')
        ->where('a.sample_info_id', $sample_info_id)
        ->select('a.manager_id', 'a.sample_info_id', 'b.realname', 'b.tester_code', 'b.partner', 'c.tester_code as partner_code')
        ->distinct()->limit(2)->get()->toArray();

        $names_str = '';
        $codes_str = '';
        if(count($tester_names) == 1) {
            # 如果仅有一条记录，
            # 则将主检人和其搭档的名字 作为检验人员
            $names_str = "{$tester_names[0]->realname}，{$tester_names[0]->partner}";
            # 则将主检人和其搭档的代号 作为检验人员
            $codes_str = "{$tester_names[0]->tester_code}，{$tester_names[0]->partner_code}";
        }else{
            # 如果有一条以上记录，则拼接所有主检人(最多2人)
            foreach($tester_names as $v) {
                $names_str .= '，'.$v->realname;
                $codes_str .= '，'.$v->tester_code;
            }
            $names_str = mb_substr($names_str,1);
            $codes_str = mb_substr($codes_str,1);
        }
        //更新 a_sample_info 表的检验人员
        DB::table('a_sample_info')->where('id', $sample_info_id)->update(['tester_names' => $names_str, 'tester_codes' => $codes_str]);
    }

    /* 审核人员 分项目结果查看 页面展示 */
    public function view(Request $request) {
        //获取 sample_info 的id
        $sample_info_id = $request->id;
        if($request->isMethod('POST')) {
            //
        }
        else {
            $where = isset($request->barCode) ? ['a.bar_code' => $request->barCode] : ['a.id' => $sample_info_id];
            $sample_info_data = DB::table('a_sample_info as a')
            ->leftJoin('a_contract as b', 'a.contract_id', '=', 'b.id')
            ->leftJoin('a_status_time as c', 'a.contract_id', '=', 'c.contract_id')
            ->select('a.*', 'b.audit_man as approve_man', 'c.approve_end')
            ->where($where)->first();
            $sample_info_id = $sample_info_data->id;

            $sample_info_data->status0 = SampleInfo::dbStat('status0')[$sample_info_data->status0];

            $gaiyao_data = DB::table('a_contract_gaiyao')->find($sample_info_data->contract_gaiyao_id);
            $cycle = DB::table('a_std_tool_rel')->where('std_id', $gaiyao_data->std_id)->where('tool_id', $gaiyao_data->tool_id)->value('cycle'); //周期
            $contract_id = $sample_info_data->contract_id;                                                                                              //批次 id
            //获取下一个样品的id
            $sample_id_next = DB::table('a_sample_info')->where('bar_code', '>', $sample_info_data->bar_code)->where('contract_id', $contract_id)->orderBy('bar_code', 'asc')->limit(1)->value('id');
            //获取上一个样品的id
            $sample_id_pre = DB::table('a_sample_info')->where('bar_code', '<', $sample_info_data->bar_code)->where('contract_id', $contract_id)->orderBy('bar_code', 'desc')->value("id");
            // dd($sample_id_next);

            $sql = "SELECT
            A.id,
            A.item_id,
            A.wea,
            A.pressure,
            A.temp,
            A.hum,
            A.remark,
            A.res,
            A.utime,
            A.manager_id,
            A.device_ids,
            A.station_ids,
            B.`name`,
            C.realname,
            D.std_id,
            D.tool_id
            FROM
            a_item_data AS A
            LEFT JOIN a_testitem AS B ON A.item_id = B.id
            LEFT JOIN manager AS C ON A.manager_id = C.id
            LEFT JOIN a_contract_gaiyao AS D ON A.contract_gaiyao_id = D.id
            LEFT JOIN a_std_tool_item_rel AS E ON D.std_id = E.std_id
            AND D.tool_id = E.tool_id
            AND A.item_id = E.testitem_id
            WHERE
            A.sample_info_id = :sample_info_id
            ORDER BY
            E.sort ASC";

            $items_data = DB::select($sql, ['sample_info_id' => $sample_info_id]);
            //获取批次的详细信息
            return view('admin.itemData.view', compact('items_data', 'sample_info_data', 'gaiyao_data', 'cycle', 'sample_id_next', 'sample_id_pre'));
        }
    }

    /* 其他项目上传结果后，自动把外观项目数据填充 */
    private function waiGUanAutoFill($sample_info_id, $data_waiGuan) {
        DB::table('a_item_data')->where([['item_id', '61'], ['sample_info_id', $sample_info_id], ['res', '2']])->update($data_waiGuan);
        if(config('constant.app_name') == 'ChongQingYuDian'){
            $itemData = DB::table('a_item_data')->where([['item_id', '61'], ['sample_info_id', $sample_info_id], ['res', '2']])->first();
            $params = ['item_id'=>$itemData->id,'res'=>$data_waiGuan['res']];
        }
    }

    /* 试验软件上传试验结果 */
    public function uploadRes(Request $request) {
        Log::info('电学PC软件--数据上传');  //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
        Log::info(json_encode($request->all())); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦

        //获取 sample_info 的 bar_code
        $bar_code = $request->bar_code;
        $inputVal = [];

        if($request->isMethod('POST')) {
            // if ($request->pwd !== config('constant.app_key')) {
            //     return '密钥错误';
            // }
            // 以上代码存在bug,暂时注释掉

            $sample_info = DB::table('a_sample_info')->where('bar_code', $bar_code)->first();
            if(!$sample_info) {
                return "未受理条码为 “{$bar_code}” 的样品";
            }

            $str_item_ids = $request->item_ids;
            $arr_item_id = explode(',', $str_item_ids); //字符串 --》数组
            $item_data_info = DB::table('a_item_data')->where('sample_info_id', $sample_info->id)->whereIn('item_id', $arr_item_id)->first();
            if(!$item_data_info) {
                return "条码为 “{$bar_code}” 的样品，未受理此检测项目";
            }
            //--------------------------------------------------------
            $item_data_id = $item_data_info->id;           //a_item_data表的id

            $commit = $item_data_info->commit;
            if($commit > 0) {
                //如果该样品已提交，则不允许保存
                return "条码为 “{$bar_code}” 的样品已提交，不允许上传";
            }
            // return "xixi";

            //获取天气和大气压力
            //$myApiController = new \App\Http\Controllers\Admin\MyApiController();
            //$wea_json = $myApiController->getWeather();
            //$wea_str = $wea_json->getContent();
            //$wea_arr = json_decode($wea_str, true);

            $res = DB::table('a_item_data')->where('id', $item_data_id)->update([
                'wea'      => $request->wea, //$wea_arr['wea'],
                'pressure' => $request->pressure, //$wea_arr['pressure'],
                'temp'     => $request->temp, 'hum' => $request->hum, 'res' => $request->res, 'utime' => $request->utime
            ]);


            /*//缓存温度 30min
            Cache::put('temp', $request->temp, 30);
            //缓存湿度 30min
            Cache::put('hum', $request->hum, 30); */

            // contract_gaiyao 的信息
            $contract_gaiyao_info = DB::table('a_contract_gaiyao')->find($sample_info->contract_gaiyao_id);
            $key_data = DB::table('a_testdata_key')->select('id')->where([['std_id', '=', $contract_gaiyao_info->std_id], ['tool_id', '=', $contract_gaiyao_info->tool_id], ['item_id', '=', $item_data_info->item_id]])->orderBy('sort')->get();

            $arr_old = $request->val;
            if(isset($arr_old[1]) && is_numeric($arr_old[1])) {
                # 存在时间t 并且 是个数字
                // 此处实现的功能是：如果时间是 1.0min 就保存 1
                $time_min = $arr_old[1]/60;
                if(sprintf('%.1f', $time_min) == sprintf('%.0f', $time_min)) {
                    $arr_old[1] = sprintf('%.0f', $time_min);
                }
                else {
                    $arr_old[1] = sprintf('%.1f', $time_min);
                }
            }

            if($arr_old) {
                # 判断$arr_old不是空数组，再进行以下操作
                $arr = [];
                foreach($arr_old as $k => $v) {
                    # code...
                    if($v !== "\\" && $v !== "/") {
                        $arr[] = $v;
                    }
                }
                //数据上传顺序 0=>U,   1=>t,   2=>L,   3=>泄漏
                foreach($key_data as $k => $v) {
                    $input_data = DB::table('a_input_data')->where([['sample_info_id', '=', $sample_info->id], ['testdata_key_id', '=', $v->id]])->first();
                    if($input_data) {
                        $inputId = $input_data->id;
                        DB::table('a_input_data')->where('id', $inputId)->update(['val' => $arr[$k]]);
                    }
                    else {
                        //如果记录不存在，则插入
                        $inputId = DB::table('a_input_data')->insertGetId(['sample_info_id' => $sample_info->id, 'testdata_key_id' => $v->id, 'val' => $arr[$k]]);
                    }

                    $inputVal[$inputId] = $arr[$k];

                    if(count($arr) === $k + 1) {
                        break;
                    }
                }
            }


            $sample_info_id = $sample_info->id;
            $data_waiGuan = [//                'wea' => $request->wea,
                             //                'pressure' => $request->pressure,
                             //                'temp' => $request->temp,
                             //                'hum' => $request->hum,
            'res' => '1', 'utime' => $request->utime
        ];

            $this->waiGUanAutoFill($sample_info_id, $data_waiGuan);                                                         // 其他项目上传结果后，自动把外观项目数据填充
            $this->updateJieLun($sample_info_id);                                                                           //更新 a_sample_info 表的 结论
            $this->updateTester($sample_info_id);                                                                           //更新 a_sample_info 表的 检验人员
            $this->updateTestTime_NextTime($sample_info_id, $contract_gaiyao_info->std_id, $contract_gaiyao_info->tool_id); //更新 a_sample_info 表的 试验时间 和 下次试验时间

            return "成功";
        }
        return 0;
    }


    //登录验证
    private function loginCheck($request){
        $num = $request->username;
        $password2 = $request->password;
        if(!$num || !$password2){
            return 0;
        }
        $res = DB::table('manager')->where('num', $num)->where('password2', $password2)->first();
        return $res;
    }


    /* 斜面机箱仪器 上传试验结果 */
    public function uploadRes2(Request $request) {
        Log::info("上传试验结果");
        if($request->device_name == "ZLCJ"){ //坠落冲击试验机
            $res = $this->uploadZLCJ($request);
            return response()->json($res)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }
        Log::info('汇邦斜面机箱仪器');
        Log::info(json_encode($request->all()));
        //新版本必须传new参数
        if(isset($request->new)) {
            header('Content-Length:20');
        }
        $inputVal = [];
        if($request->isMethod('POST') or true) {
            /* if ($request->pwd !== "HeBeiDianKeYuan_lsfhdgjhjdkghdeuplj") {
                return '密钥错误';
            } */
            switch($request->id) {
                case '0': # ========================================================= 登录验证
                    $res = $this->loginCheck($request);
                    // Log::info('登录验证：'.json_encode($res));
                    if($res) {
                            # 验证通过
                        // info('0000000');
                        return "start{0}end";
                    }
                    else {
                        // info('1111111');
                            # 验证不通过
                        return "start{1}end";
                            // return $request->username . $request->password .'bbb';
                    }
                break;
                case '3': # ========================================================= HB5876向服务器读取温度
                    $date = date('Y-m-d H:i:s', strtotime('-30 minute'));
                    $id = 1;
                    $fac_num = request('fac_num','');
                    if ($fac_num) {
                        try{
                            $station = DB::table('a_station')->where('fac_num',$fac_num)->first();
                            $tempDevNum = $station->temp_hum_num;
                            $id = DB::table('a_hb6303')->where('dev_num',$tempDevNum)->value('id');
                        }catch(\Exception $exception){

                        }
                    }
                    $temp = DB::table('a_env_info')->where('hb6303_id', $id)->where('time', '>', $date)->orderBy('id', 'desc')->value('temp');
                    if(!$temp) {
                            # 没有查到温度
                        $temp = - 99.9;
                    }
                    $temp = sprintf('%+05.1f', $temp); // +03.6
                    $ret = "start{".$temp."}end";
                    //新版本必须传new参数
                    if(isset($request->new)) {
                        header('Content-Length:'.strlen($ret));
                    }
                    return $ret;
                    break;
                case '1': # ========================================================= 试验结果上传
                    # 试验结果上传
                    // return "start{0}end"; // 上传成功------------测试用的代码

                    //获取 sample_info 的 bar_code
                    $bar_code = $request->bar_code;
                    $num = $request->username; //工号

                    $manager_id = DB::table('manager')->where('num', $num)->value('id');
                    if(!$manager_id) {
                        return "start{1}end"; //"工号 “{$工号}” 无效";
                    }

                    $sample_info = DB::table('a_sample_info')->where('bar_code', $bar_code)->first();
                    if(!$sample_info) {
                        return "start{2}end"; //"未受理条码为 “{$bar_code}” 的样品";
                    }


                    if($request->device_name === 'JDXCZ') {
                        $str_item_ids = "1,5";
                    }
                    else {
                        $str_item_ids = $request->item_ids;
                    }
                    $arr_item_id = explode(',', $str_item_ids); //字符串 --> 数组
                    $item_data_info = DB::table('a_item_data')->where('sample_info_id', $sample_info->id)->whereIn('item_id', $arr_item_id)->first();
                    if(!$item_data_info) {
                        return "start{3}end"; //"条码为 “{$bar_code}” 的样品，未受理此检测项目";
                    }

                    if($manager_id !== $item_data_info->manager_id) {
                        return "start{4}end"; //此任务未分配给您
                    }
                    //--------------------------------------------------------
                    $item_data_id = $item_data_info->id;           //a_item_data表的id

                    $commit = $item_data_info->commit;
                    if($commit > 0) {
                        //如果该样品已提交，则不允许保存
                        return "start{5}end"; // "条码为 “{$bar_code}” 的样品已提交，不允许上传";
                    }

                    //获取天气和大气压力
                    //$myApiController = new \App\Http\Controllers\Admin\MyApiController();
                    //$wea_json = $myApiController->getWeather();
                    //$wea_str = $wea_json->getContent();
                    //$wea_arr = json_decode($wea_str, true);


                    /*//缓存温度 30min
                    Cache::put('temp', $request->temp, 30);
                    //缓存湿度 30min
                    Cache::put('hum', $request->hum, 30); */

                    // contract_gaiyao 的信息
                    $contract_gaiyao_info = DB::table('a_contract_gaiyao')->find($sample_info->contract_gaiyao_id);
                    $key_data = DB::table('a_testdata_key')->select('id')->where([['std_id', '=', $contract_gaiyao_info->std_id], ['tool_id', '=', $contract_gaiyao_info->tool_id], ['item_id', '=', $item_data_info->item_id]])->orderBy('sort')->get();

                    $arr = $oldV = $request->v;
                    if($request->device_name === 'DDXDZ') {
                        # 导电鞋电阻 时间单位 秒 转 分
                        $arr[1] = sprintf('%.0f', $arr[1]/60);
                    }

                    $temp = '';
                    if($arr) {
                        # 判断$arr不是空数组，再进行以下操作
                        if($request->device_name === 'JDXCZ') {
                            # 如果仪器是 接地线成组电阻 重新调整 $arr
                            $count_arr = count($arr);
                            $new_arr = [];
                            for($i = 2; $i < $count_arr; $i ++) {
                                if($i >= 3 && $i <= 7) {
                                    # 单位换算：mm 转为 cm
                                    $new_arr[] = $arr[$i]/10;
                                }
                                else {
                                    # code...
                                    if($arr[$i] === '') {
                                        $new_arr[] = '—';
                                    }
                                    else {
                                        $new_arr[] = $arr[$i];
                                    }
                                }
                            }
                            $temp = $arr[2];
                            $arr = $new_arr;

                            if(isset($oldV[18])) {
                                for($i = 16; $i < 26; $i ++) {
                                    $arr[$i] = $oldV[$i + 2] ? $oldV[$i + 2] : '—';
                                }
                            }
                            else {
                                $arr[16] = $arr[6] === '—' ? '—' : 100*$arr[6]/(($arr[1] + $arr[5])*(1 + 0.00393*($arr[0] - 20)));   //AN每米电阻  计算公式：r20=100*R/[L(1+α*(t-20))] ,α=0.00393
                                $arr[17] = $arr[7] === '—' ? '—' : 100*$arr[7]/(($arr[2] + $arr[5])*(1 + 0.00393*($arr[0] - 20)));   //BN每米电阻
                                $arr[18] = $arr[8] === '—' ? '—' : 100*$arr[8]/(($arr[3] + $arr[5])*(1 + 0.00393*($arr[0] - 20)));   //CN每米电阻
                                $arr[19] = $arr[9] === '—' ? '—' : 100*$arr[9]/(($arr[4] + $arr[5])*(1 + 0.00393*($arr[0] - 20)));   //0N每米电阻
                                $arr[20] = $arr[10] === '—' ? '—' : 100*$arr[10]/(($arr[1] + $arr[4])*(1 + 0.00393*($arr[0] - 20))); //A0每米电阻
                                $arr[21] = $arr[11] === '—' ? '—' : 100*$arr[11]/(($arr[2] + $arr[4])*(1 + 0.00393*($arr[0] - 20))); //B0每米电阻
                                $arr[22] = $arr[12] === '—' ? '—' : 100*$arr[12]/(($arr[3] + $arr[4])*(1 + 0.00393*($arr[0] - 20))); //C0每米电阻
                                $arr[23] = $arr[13] === '—' ? '—' : 100*$arr[13]/(($arr[1] + $arr[3])*(1 + 0.00393*($arr[0] - 20))); //AC每米电阻
                                $arr[24] = $arr[14] === '—' ? '—' : 100*$arr[14]/(($arr[2] + $arr[3])*(1 + 0.00393*($arr[0] - 20))); //BC每米电阻
                                $arr[25] = $arr[15] === '—' ? '—' : 100*$arr[15]/(($arr[1] + $arr[2])*(1 + 0.00393*($arr[0] - 20))); //AB每米电阻

                                for($i = 16; $i < 26; $i ++) {
                                    if($arr[$i] !== '—') {
                                        $arr[$i] = sprintf('%06.4f', $arr[$i]); //$temp = sprintf('%+05.1f', $temp);// +03.6
                                    }
                                }
                            }

                            $arr[0] = $arr[16];
                            for($i = 17; $i < 26; $i ++) {
                                //取最大值
                               if ($arr[$i] != '—' && $arr[0] < $arr[$i]) {
                                  $arr[0] = $arr[$i];
                              }
                          }
                          Log::info('JDXCZ计算结果：');
                            Log::info(json_encode($arr));//该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
                        }

                        Log::info('keydata:'.json_encode($key_data));
                        foreach($key_data as $k => $v) {
                            $input_data = DB::table('a_input_data')->where([['sample_info_id', '=', $sample_info->id], ['testdata_key_id', '=', $v->id]])->first();

                            if($input_data) {
                                $inputId = $input_data->id;
                                DB::table('a_input_data')->where('id', $inputId)->update(['val' => $arr[$k]]);
                            }
                            else {
                                //如果记录不存在，则插入
                                $inputId = DB::table('a_input_data')->insertGetId(['sample_info_id' => $sample_info->id, 'testdata_key_id' => $v->id, 'val' => $arr[$k]]);
                            }

                            $inputVal[$inputId] = $arr[$k];

                            if(count($arr) === $k + 1) {
                                break;
                            }
                        }
                    }

                    $res = request('res',2);
                    //结论,0-不符合，1-符合，2-未录入
                    switch($request->device_name) {
                        case 'DDXDZ': //导电鞋电阻
                            # < 100kΩ 合格
                        if($arr[2] != '') {
                            if($arr[2][0] == '>' || $arr[2] >= 100000) {
                                $res = 0;
                            }
                            else {
                                $res = 1;
                            }
                        }

                        break;
                        case 'PBFDZ':
                            # 整套屏蔽服装 <= 20 Ω 合格
                            # 上衣        <= 15 Ω 合格
                            # 裤子        <= 15 Ω 合格
                            # 袜子        <= 15 Ω 合格
                            # 手套        <= 15 Ω 合格
                            # 导电鞋      <= 500 Ω 合格
                        $res = 1;
                        if($arr[0] != '') {
                            if($arr[0][0] == '>' || $arr[0] > 20) {
                                $res = 0;
                            }
                        }
                        if($arr[1] != '') {
                            if($arr[1][0] == '>' || $arr[1] > 15) {
                                $res = 0;
                            }
                        }
                        if($arr[2] != '') {
                            if($arr[2][0] == '>' || $arr[2] > 15) {
                                $res = 0;
                            }
                        }
                        if($arr[3] != '') {
                            if($arr[3][0] == '>' || $arr[3] > 15) {
                                $res = 0;
                            }
                        }
                        if($arr[4] != '') {
                            if($arr[4][0] == '>' || $arr[4] > 15) {
                                $res = 0;
                            }
                        }
                        if($arr[5] != '') {
                            if($arr[5][0] == '>' || $arr[5] > 500) {
                                $res = 0;
                            }
                        }
                        break;
                        case 'PBFXL':
                            //屏蔽服效率

                            # 750kV 及以下 >= 40dB 合格
                            # 特高压       >= 60dB 合格

                            # 屏蔽面罩     >= 20dB 合格
                        $res = $arr[0] >= 40 ? 1 : 0;
                        break;

                        default:
                            # code...
                        break;
                    }

                    DB::table('a_item_data') ->where('id', $item_data_id) ->update([// 'wea' => '晴', //$wea_arr['wea'],
                                // 'pressure' => '100', //$wea_arr['pressure'],
                                'temp' => $temp, // 'hum' => $request->hum,
                                'res'  => $res// 'utime' => $request->utime
                            ]);

                    //录入结果后，分析一下当前样品的所有项目的结果情况
                    // 结论, 0 - 不符合，1 - 符合，2 - 未录入
                    //如果所有项目全部符合即合格，等价于 不符合或未录入的记录数为0
                    $sql = "SELECT
                    count( 1 ) AS count
                    FROM
                    a_item_data
                    WHERE
                    sample_info_id = :sample_info_id
                    AND ( res = 0 OR res = 2 ) ";

                    $count = DB::select($sql, ['sample_info_id' => $sample_info->id]);
                    $count = $count[0]->count;
                    if($count === 0) {
                        DB::table('a_sample_info')->where('id', $sample_info->id)->update(['res' => '1']); //合格
                    }
                    else {
                        //如果存在不符合的记录，说明此样品不合格
                        $count = DB::table('a_item_data')->where([['sample_info_id', '=', $sample_info->id], ['res', '=', '0']])->count();
                        if($count > 0) {
                            DB::table('a_sample_info')->where('id', $sample_info->id)->update(['res' => '2']); //不合格
                        }
                        else {
                            DB::table('a_sample_info')->where('id', $sample_info->id)->update(['res' => '0']); //未完成
                        }
                    }
                    $sample_info_id = $sample_info->id;
                    $this->updateTester($sample_info_id);                                                                                                                   //更新 a_sample_info 表的检验人员

                    //更新 a_sample_info 表的试验时间
                    // $test_time = date("Y/m/d"); //把当前时间作为检测时间
                    $test_time = DB::table('a_item_data')->where('sample_info_id', $sample_info->id)->max('utime');                                                         //把当前样品所有检测项目的最新检测时间作为检测时间
                    $r = DB::table('a_sample_info')->where('id', $sample_info->id)->update(['test_time' => $test_time]);

                    //获取检验周期
                    $cycle = DB::table('a_std_tool_rel')->where('std_id', $contract_gaiyao_info->std_id)->where('tool_id', $contract_gaiyao_info->tool_id)->value('cycle'); //周期
                    $cycle = intval($cycle*12);
                    if($cycle > 0) {
                        $valid_date = date("Y-m-d", strtotime("+$cycle month", strtotime($test_time)));
                        $first_date = date("Y-m-d", strtotime("first day of +$cycle month", strtotime($test_time)));
                        if(substr($valid_date, 0, 7) !== substr($first_date, 0, 7)) {
                            $valid_date = date("Y-m-d", strtotime("last day of +$cycle month", strtotime($test_time)));
                        }

                        $valid_date = date('Y-m-d', strtotime("-1 day", strtotime($valid_date)));
                        //更新 a_sample_info 表的下次试验时间
                        DB::table('a_sample_info')->where('id', $sample_info->id)->update(['next_time' => $valid_date]);
                    }
                    return "start{0}end"; // 上传成功
                    break;
                case '4': #### 仪器操作过程,无返回
                $this->upDevStat();
                break;
                default:
                    # code...
                break;
            }
        }
    }

    private function upDevStat() {
        /* *
            id=4&  // 功能码，此处固定为4
            item_ids=5& //试验项目id，与数据库的id 一致
            username=000064&  //  工号
            device_num=123456& //仪器编号
            bar_code=111111111& //操作中的条形码编号
            status=1& //设备状态：1新录条形码；2实验中；3上传试验结果
         * */
            $params = request()->all();
            $statusNo = $params['status'];
            $data = [
                'statusNo' => $statusNo,
                'statuStr' => $this->getStat($statusNo),
                'bar_code' => $params['bar_code']
            ];
            $data = json_encode($data);
            $client = new \Mosquitto\Client();
            $client->onConnect(function($r) {
                dump("I got code {$r}\n");
            });
            $client->onDisconnect(function() {
                dump("Disconnected cleanly\n");
            });
            $client->onPublish(function() use ($client) {
                dump("Mesage published\n");
                $client->disconnect();
            });
            $client->connect("127.0.0.1", 1883, 60);
            $client->publish('/one2one/station/'.$params['device_num'], $data);
            $client->disconnect();
        }

    /*
     *  status=1& //设备状态：1新录条形码；2实验中；3上传试验结果
     */
    private function getStat($status) {
        switch($status) {
            case 1:
            $statuStr = '正在录入样品...';
            break;
            case 2:
            $statuStr = '试验中...';
            break;
            case 3:
            $statuStr = '正在上传试验结果...';
            break;
        }
        return $statuStr;
    }

    //手机扫描二维码查看试验记录
    public function viewRes(Request $request) {
        // return redirect("/admin/itemData/view?id={$request->id}");

        //获取 sample_info 的id
        $sample_info_id = $request->id;
        $key = $request->k ?: $request->key; //密钥

        if($request->isMethod('POST')) {
            //
        }
        else {
            $sample_info_data = DB::table('a_sample_info')->find($sample_info_id);
            if(!$sample_info_data) {
                # 如果返回null,直接返回
                return;
            }
            if($sample_info_data->key != $key) {
                return "<h1 style='margin-top:200px;padding-left:50px'>密钥错误</h1>";
            }
            $gaiyao_data = DB::table('a_contract_gaiyao as a')->leftJoin('a_contract as b', 'a.contract_id', '=', 'b.id')->select('a.*', 'b.client_name')->where('a.id', $sample_info_data->contract_gaiyao_id)->first();
            //            $gaiyao_data = DB::table('a_contract_gaiyao')->find($sample_info_data->contract_gaiyao_id);
            $cycle = DB::table('a_std_tool_rel')->where('std_id', $gaiyao_data->std_id)->where('tool_id', $gaiyao_data->tool_id)->value('cycle'); //周期
            //  $contract_id = $sample_info_data->contract_id; //批次 id
            //获取下一个样品的id
            //  $sample_id_next = DB::table('a_sample_info')->where('id', '>', $sample_info_id)->where('contract_id', $contract_id)->orderBy('id', 'asc')->value("id");
            //获取上一个样品的id
            //  $sample_id_pre = DB::table('a_sample_info')->where('id', '<', $sample_info_id)->where('contract_id', $contract_id)->orderBy('id', 'desc')->value("id");

            $sql = "SELECT
            A.id,
            A.item_id,
            A.wea,
            A.pressure,
            A.temp,
            A.hum,
            A.res,
            A.manager_id,
            A.device_ids,
            A.remark,
            B.`name`,
            C.realname,
            D.std_id,
            D.tool_id
            FROM
            a_item_data AS A
            LEFT JOIN a_testitem AS B ON A.item_id = B.id
            LEFT JOIN manager AS C ON A.manager_id = C.id
            LEFT JOIN a_contract_gaiyao AS D ON A.contract_gaiyao_id = D.id
            LEFT JOIN a_std_tool_item_rel AS E ON D.std_id = E.std_id
            AND D.tool_id = E.tool_id
            AND A.item_id = E.testitem_id
            WHERE
            A.sample_info_id = :sample_info_id
            ORDER BY
            E.sort ASC";

            $items_data = DB::select($sql, ['sample_info_id' => $sample_info_id]);
            //历史信息
            if($sample_info_data->gqj_ID !== '' && intval($sample_info_data->gqj_ID) !== 0) {
                $history = DB::table('a_sample_info')->where('bar_code', '!=', $sample_info_data->bar_code)->where('gqj_ID', $sample_info_data->gqj_ID)->whereNotNull('test_time')->select('test_time', 'id', 'key')->orderBy('test_time', 'desc')->get();
            }
            else {
                $history = [];
            }
            //获取批次的详细信息
            $app_name = config('constant.app_name');
            if (file_exists(base_path().'/resources/views/admin/itemData/viewRes/'.$app_name.'.blade.php')){
              return view('admin.itemData.viewRes/'.$app_name, compact('items_data', 'sample_info_data', 'gaiyao_data', 'cycle', 'history'));
          }
          return view('admin.itemData.viewRes', compact('items_data', 'sample_info_data', 'gaiyao_data', 'cycle', 'history'));
      }
  }

    //温湿度气压计页面
    public function temHuiPreIndex() {
        if(request()->isMethod('POST')) {
                //缓存温度 30min
            Cache::put('temp', request('temp', ''), 30);
                //缓存湿度 30min
            Cache::put('hum', request('hum', ''), 30);

                //缓存天气 60*4 min
            Cache::put('wea', request('wea', '晴'), 60*4);
                //缓存气压 60*4 min
            Cache::put('pressure', request('pressure', ''), 60*4);
            return 1;
        }
        return view('admin.itemData.temHuiPreIndex');
    }

    //坠落冲击试验数据上传
    private function uploadZLCJ($request){
        Log::info("坠落冲击力学试验");
        Log::info(json_encode($request->all()));
        if(!$request->isMethod('post') or false){
            return rtdata(0,"请求方式错误！");
        }
        switch($request->id) {
            case '0': # ========================================================= 登录验证
                $res = $this->loginCheck($request);
                return $res ? rtdata(1,'1') : rtdata(0,'2');
            break;
            case "1": # ========================================================= 上传实验结果
                return $this->uploadZLCJres($request);
            break;
            case "3": # ========================================================= 获取温湿度大气压
                $data = [];
                $hb6303 = DB::table('a_env_info')->where('dev_num',$request->hb6303)->orderBy('id','desc')->first();
                if ($hb6303) {
                    $data['temp'] = $hb6303->temp;
                    $data['humi'] = $hb6303->humi;
                    $data['pressure'] = $hb6303->pressure;
                }
                $qingping = DB::table('a_env_info')->where('dev_num',$request->qingping)->orderBy('id','desc')->first();
                if ($qingping) {
                    if ($request->hb6303) {
                        $data['pressure'] = $qingping->pressure;
                    }else{
                        $data['temp'] = $qingping->temp;
                        $data['humi'] = $qingping->humi;
                        $data['pressure'] = $qingping->pressure;
                    }
                }
                return rtdata(1,'success',$data);
            break;
            default:
                return rtdata(0,'请求错误！');
            break;
        }
    }
    private function uploadZLCJres($request){
        // http://z.gqjjc03.vip/api/test/uploadRes2?id=1&bar_code=220002002&username=000064&device_name=ZLCJ&ZLCJ_F_max=1&ZLCJ_L_slide=2&ZLCJ_L_ext=3&ZLCJ_oscillogram=
        $post_data = $request->all();
        $num = $post_data['username']; //工号
        if(!$num){
            return rtdata(0,'请先登录！');
        }
        //试品信息
        $sample_info = DB::table('a_sample_info as a')
                      ->leftJoin('a_item_data as b','b.sample_info_id','=','a.id')
                      ->leftJoin('manager as c','c.id','=','b.manager_id')
                      ->where('a.bar_code',$post_data['bar_code'])
                      ->where('c.num',$num)
                      ->select('a.id','a.bar_code','c.num')
                      ->first();
        if (!$sample_info) {
            return rtdata(0,'编码或任务分配错误！');
        }
        //整理inputdata信息
        $input_data = DB::table('a_input_data as a')
                    ->leftJoin('a_testdata_key as b','a.testdata_key_id','=','b.id')
                    ->where('a.sample_info_id',$sample_info->id)
                    ->where('b.station_up_param','!=','')
                    ->select('a.*','b.station_up_param')
                    ->get()->keyBy('station_up_param');
        $data_up_input = [];
        foreach ($input_data as $station_up_param => $item) {
            if(!isset($post_data[$station_up_param])){
                continue;
            }
            if ($station_up_param == 'ZLCJ_oscillogram') {
                $base64_img = $post_data[$station_up_param];
                if($base64_img){
                    $filename = "坠落冲击波形图_{$post_data['bar_code']}_{$item->id}";
                    $uploadcon = new UploadController();
                    $res = $uploadcon->render('img', [
                        'dir' => 'input_data',
                        'file' => $base64_img,
                        'filename' => $filename,
                        'rotate' => 1,
                        'size_max' => 1024, //最大1M
                        'text_x' => 400,
                    ]);
                    if($res['code'] == 1){
                        $post_data[$station_up_param] = $res['data']['path'];
                    }else{
                        return $res;
                    }
                }else{
                    $post_data[$station_up_param] = '';
                }
            }

            if ($station_up_param == 'ZLCJ_oscillogram') {
                $base64_img = $post_data[$station_up_param];
                if($base64_img){
                    $filename = "坠落冲击波形图_{$post_data['bar_code']}_{$item->id}";
                    $uploadcon = new UploadController();
                    $res = $uploadcon->render('img', [
                        'dir' => 'input_data',
                        'file' => $base64_img,
                        'filename' => $filename,
                        'rotate' => 1,
                        'size_max' => 1024, //最大1M
                        'text_x' => 400,
                    ]);
                    if($res['code'] == 1){
                        $post_data[$station_up_param] = $res['data']['path'];
                    }else{
                        return $res;
                    }
                }else{
                    $post_data[$station_up_param] = '';
                }
            }

            $data_up_input[$item->id] = $post_data[$station_up_param];
        }
        $ZLCJ_oscillogram_data = [
            'xy_name' => isset($post_data['xy_name']) ? $post_data['xy_name'] : [],
            'xy_unit' => isset($post_data['xy_unit']) ? $post_data['xy_unit'] : [],
            'x_data' => isset($post_data['x_data']) ? $post_data['x_data'] : [],
            'y_data' => isset($post_data['y_data']) ? $post_data['y_data'] : [],
        ];

        // dd($data_up_input,$post_data);
        $res = $request->res;
        $wea = $request->wea;
        $wea = $wea==0 ? '晴' : ($wea==1 ? '阴' : ($wea==2 ? '雨' : ($wea==3 ? '雪' : '未知')));
        $upItemdata = [
            'wea'=> $wea,  //0-晴，1-阴，2-雨，3-雪
            'temp'=>$request->temp,
            'hum'=>$request->humi,
            'pressure'=>$request->pressure,
            'res'=> $res,
        ];
        // dd($request->all(),$input_data);
        try {
            DB::transaction(function() use ($sample_info, $upItemdata, $data_up_input) {
                DB::table('a_item_data')->where('sample_info_id',$sample_info->id)->update($upItemdata);
                $this->updateTester($sample_info->id);  //更新 a_sample_info 表的 检验人员
                foreach ($data_up_input as $id => $val) {
                    DB::table('a_input_data')->where('id',$id)->update(['val'=>$val]);
                }
            });
        } catch(\Throwable $e) {
            // dd($e->getMessage());
            return rtdata(0,$e->getMessage());
        }


        $this->updateTestTime_NextTime($sample_info_id, $contract_gaiyao_info->std_id, $contract_gaiyao_info->tool_id); //更新 a_sample_info 表的 试验时间 和 下次试验时间

        return rtdata(1,'数据上传成功！');
    }
}
